﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tetris
{
    class CollisionDispatcher
    {
        public static bool HandleCollisions(Figure movingFigure, SortedSet<Figure> staticFigures, Direction d, int worldRows, int worldCols)//return true if collision occured
        {
            char[,] image = movingFigure.GetImage();

            if (d == Direction.Down && movingFigure.GetTopLeft().Row + image.GetLength(0) > worldRows)
            {
                movingFigure.Move(Direction.Up);
                if (d == Direction.Down)
                {
                    movingFigure.RespondToCollision();
                }
                return true;
            }

            for (int r = 0; r < image.GetLength(0); r++)
            {
                for (int c = 0; c < image.GetLength(1); c++)
                {
                    if (image[r,c] != ' ' && staticFigures.Contains(
                        new Block(new MatrixCoords(movingFigure.GetTopLeft().Row + r, movingFigure.GetTopLeft().Col + c))))
                    {
                        movingFigure.Move(CollisionDispatcher.GetOppositeDirection(d));
                        if (d == Direction.Down)
                        {
                            movingFigure.RespondToCollision();
                        }
                        return true;
                    }
                }
            }

            return false;
        }

        private static Direction GetOppositeDirection(Direction d)
        {
            switch (d)
            {
                case Direction.Down: return Direction.Up;
                case Direction.Left: return Direction.Right;
                case Direction.Right: return Direction.Left;
                default: return Direction.Down;
            }
        }
    }
}
